package chans

import "context"

type Enable struct {
	e      *Entity
	fn     func(ctx context.Context)
	ctx    context.Context
	cancel context.CancelFunc
}

func NewEnable(fn func(ctx context.Context)) {
	e := &Enable{e: NewEntity(1)}
	e.e.SetHandler(func(no, num int, data interface{}) {
		if data != nil {
			data.(func(ctx context.Context))(e.ctx)
		}
	})
}

func (this *Enable) Enable(b bool) *Enable {
	if this.cancel != nil {
		this.cancel()
	}
	this.ctx, this.cancel = context.WithCancel(context.Background())
	if !b {
		this.e.Do(func(ctx context.Context) { <-ctx.Done() })
		return this
	}
	this.e.Do(this.fn)
	return this
}
